package com.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import net.sf.json.JSONObject;

/**
 * 陪聊接口
 * 天气：msg=天气深圳
中英翻译：msg=翻译i love you
　藏头诗：msg=藏头诗春节快乐
　歌词⑴：msg=歌词后来
　歌词⑵：msg=歌词后来-刘若英
　　笑话：msg=笑话
　计算⑴：msg=计算1+1*2/3-4
　计算⑵：msg=1+1*2/3-4
　域名⑴：msg=域名ajaxsns.com
　域名⑵：msg=ajaxsns.com
　ＩＰ⑴：msg=归属127.0.0.1
　ＩＰ⑵：msg=127.0.0.1
　手机⑴：msg=归属13430107662
　手机⑵：msg=13430107662
智能聊天：msg=你好
 * @author Jason
 *
 */
public class ChatWith {

	/**
	 * 获取指定地址的内容
	 * @param urlStr
	 * @return
	 */
		public static String getContent(String urlStr){
			URL url = null;
			BufferedReader br = null;
			StringBuffer sb = null;
			try {
				url = new URL(urlStr);
				URLConnection urlconn = url.openConnection();
				urlconn.setConnectTimeout(3000);
				br = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
				String temp = "";
				sb = new StringBuffer();
				while((temp = br.readLine()) != null){
					sb.append(temp);
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			} finally{
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}
	
		public static String chat(String name){
			String url = null;
			try {
				url = "http://api.ajaxsns.com/api.php?key=free&appid=0&msg=" +
						URLEncoder.encode(name, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String content = getContent(url);
			if(content == null){
				return "我们聊点别的吧，好无聊啊~";
			}
			JSONObject jsonObj = JSONObject.fromObject(content);
			String str = jsonObj.getString("content");
			str = str.replaceAll("\\{br\\}", "<br>");
			return str;
		}
		
		public static String kuaidi(String[] name){
			if(name.length < 2){
				return "您输入的快递公司名称和运单号不合法哦！";
			}
			String url = null;
			try {
				url = "http://www.weinxinma.com/api/index.php?m=Express&a=index&name="+
						URLEncoder.encode(name[0], "utf-8")+"&number="+
						URLEncoder.encode(name[1], "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String content = getContent(url);
			return content;
		}
		
		public static void main(String[] args) throws Exception{
			System.out.println(chat("糗事"));
		}
		
		public static String langdu(String name){
			String url = null;
			try {
				url = "http://www.apiwx.com/aaa.php?w="+URLEncoder.encode(name,"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String content = getContent(url);
			
			return content;
		}
}
